package xin.pms.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import xin.core.jpa.JpaConstant;
import xin.core.jpa.model.SimpleSortableEntity;
import xin.pms.request.RoleRequest;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

/**
 * <pre>
 * Role Model
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.
 * @since 2018/7/28 14:50
 */
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "pms_role")
@Data
@ToString(exclude = {"users","permissions","groups"})
@EqualsAndHashCode(callSuper = true, of = {})
public class Role extends SimpleSortableEntity implements Serializable {

    @Id
    @Column(length = JpaConstant.CommonStringLength)
    private String code;

    /**
     * 用户
     */
    @JsonIgnore
    @ManyToMany(mappedBy = "roles")
    private List<User> users;

    /**
     * 权限
     */
    @JsonIgnore
    @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE})
    @OrderBy("priority desc")
    @JoinTable(name = "pms_role_permission", joinColumns = {
            @JoinColumn(name = "role_id", nullable = false, updatable = false) }, inverseJoinColumns = {
            @JoinColumn(name = "permission_id", nullable = false, updatable = false) })
    private List<Permission> permissions;

    public Role(RoleRequest request) {
        this.name = request.getName();
        this.code = request.getCode();
        this.description = request.getDescription();
    }
}

